import { createStore } from 'vuex'

import homeModule from './modules/home'
import counterModule from './modules/counter'
const store = createStore({
  state: () => ({
    // counter: 100,
    name: 'why',
    level: 1,
    age: 18,
    height: 1.88,
    users: [
      { age: 18, name: 'why' },
      { age: 19, name: 'why' },
      { age: 20, name: 'why' },
      { age: 21, name: 'why' },
      { age: 22, name: 'why' },
    ],
    banners: [],
  }),
  getters: {
    doubleCounter(state) {
      return state.counter + 2
    },
    doubleTotalAge(state) {
      return state.users.reduce((preVlaue, item) => {
        // console.log(preVlaue, item)
        return preVlaue + item.age
      }, 0)
    },
    message(state, getters) {
      return `name:${state.name} userTaotalAge:${getters.doubleTotalAge}`
    },
    getUser(state) {
      return function (age) {
        const user = state.users.find((item) => {
          return item.age === age
        })
        return user
      }
    },
  },
  mutations: {
    add() {
      this.state.counter++
    },
    changeName(state, payload) {
      this.state.name = 'kob'

      // console.log(payload)
      this.state.counter += payload.counter
    },
    changeBanner(state, banner) {
      this.state.banners = banner
    },
  },
  actions: {
    incrementAction(context, payload) {
      // console.log(context)
      // console.log(context.state)
      // console.log(context.commit)
      // console.log(context.getters)
      // console.log(payload)
      context.commit('add')
    },
    async asynAction(content) {
      //  fetch("http://123.207.32.32:8000/home/multidata").then(res=>{
      //   res.json().then(data=>{
      //     console.log(data)
      //   })
      //  })

      //
      //
      // fetch('http://123.207.32.32:8000/home/multidata')
      //   .then((res) => {
      //     return res.json()
      //   })
      //   .then((data) => {
      //     console.log(data)
      //   })

      //await
      const res = await fetch('http://123.207.32.32:8000/home/multidata')
      const data = await res.json()
      console.log(data)
      //修改state
      content.commit('changeBanner', data.data.banner.list)
      //   return new Promise(async (resolve, reject) => {
      //     // 3.await/async
      //     const res = await fetch("http://123.207.32.32:8000/home/multidata")
      //     const data = await res.json()
      //     // 修改state数据
      //     context.commit("changeBanners", data.data.banner.list)
      //     context.commit("changeRecommends", data.data.recommend.list)
      //     resolve("aaaaa")
      //   })
      // }
    },
  },
  modules: {
    home: homeModule,
    counter: counterModule
  }
})

export default store
